#include "counterpartFormatString.h"
#include "counterpartExceptions.h"

#include <boost/scoped_array.hpp>
#include <stdarg.h>
#include <stdio.h>

using namespace std;
using namespace boost;

FormatString::FormatString (const char * format, ...)
{
	DeclareSimpleException (vsnprintfFailed);

	va_list argList;
	va_start (argList, format);

		int bytesNeeded (vsnprintf (NULL, 0, format, argList));
		if (bytesNeeded < 0) Throw (vsnprintfFailed ( ));

	va_end (argList);

	// documentation says vsnprintf leaves argList in an undefined state

	va_start (argList, format);

		scoped_array <char> buffer (new char [bytesNeeded + 1]);
		int actualBytes (vsnprintf (buffer.get ( ), bytesNeeded + 1, format, argList));
		if (actualBytes < 0) Throw (vsnprintfFailed ( ));
		assert (actualBytes == bytesNeeded);

		(void) assign (buffer.get ( ));

	va_end (argList);
}
